/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.mvc.views.effect
{
	import com.puny.mvc.views.View;
	
	public class SoundCatalogView extends View
	{
		private static var _myself:SoundCatalogView;
		
		
		private const _sounds:Object = new Object();
		private var _config:XML;
		
		/**
		 * 
		 * @param config
		 * @param src
		 * @return 
		 * @example sample configuration
		 * <listing version="3.0">
		 * &lt;sounds&gt;
		 * &lt;sound id=&quot;fire&quot; exported=&quot;fireUpSound&quot;/&gt;
		 * &lt;sound id=&quot;jump&quot; url=&quot;http://www.mysounds.com/sfx/button_click.mp3&quot;/&gt;
		 * &lt;/sounds&gt;
		 * </listing>
		 */
		public function SoundCatalogView(config:XML=null, src:Object=null)
		{
			_config = config;
			super(src);
		}
		
		override protected function setup():void {
			var obj:Object;
			for each(var objs:XML in _config.sounds) {
				for each(var sound:XML in objs.sound) {
					if (sound.hasOwnProperty("@instances") && int(sound.@instances) > 1) {
						_sounds[sound.@id] = new Array();
						for (var i:int = 0;i < int(sound.@instances);i++) {
							_sounds[sound.@id].push(prepareSound(sound));
						}
					} else {
						_sounds[sound.@id] = prepareSound(sound);
					}
				}
			}
		}
		
		private function prepareSound(sound:XML):SoundView {
			var obj:Object;
			if (sound.hasOwnProperty("@exported")) {
				obj = getSound(sound.@exported);
			} else {
				obj = sound.@url;
			}
			var soundView:SoundView = addSound(obj);
			if (sound.hasOwnProperty("@volume")) {
				soundView.volume = Number(sound.@volume);
			}
			return addSound(obj);
		}
		
		public function play(id:String, loop:Boolean = false):void {
			var sound:SoundView;
			if (_sounds[id] is Array) {
				sound = _sounds[id].shift();
				_sounds[id].push(sound);
			} else {
				sound = _sounds[id];
			}
			sound.play(loop);
		}

		public function stopAllSounds():void {
			for each(var item:* in _sounds) {
				if (item is Array) {
					item.forEach(stopChildren);
				} else {
					item.stop();
				}
			}
		}

		private function stopChildren(item:SoundView, index:int, arr:Array):void {
			item.stop();
		}
		
	}
}
